<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Request;
use Yeepay\Yop\Sdk\V1\YopConfig;
use Yeepay\Yop\Sdk\V1\YopRequest;
use Yeepay\Yop\Sdk\V1\YopRsaClient;
use sandpay\HmPayClient;
/**
 * 首页接口
 */
class Admindata extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();

//      if (!Config::get('fastadmin.usercenter')) {
//          $this->error(__('User center already closed'));
//      }

    }
    /**
     * 商品接口
     *
     */
    public function goodslist(Request $request)
    {
    	$store_no = $this->request->post('store_no');
    	$name = $this->request->post('name');
    	$where = [];
    	$whereOr = [];
    	if($name)
    	{
    		$where['goods_name'] = ['like', '%' . $name . '%'];
    		$whereOr['sku'] = ['like', '%' . $name . '%'];
    	}
    	$data = \app\admin\model\goods_manage\Goods::where('store_no', $store_no)->where($where)->whereOr($whereOr)->select();

        $this->success('请求成功',$data);
    }
    
    /**
     * 油枪
     *
     */
    public function getoil()
    {
    	$store_no = $this->request->post('store_no');
    	$oil_list = \app\admin\model\gas\Gasset::where('store_no', $store_no)->select();
    	foreach ($oil_list as $index => $item) {
    		$item['gun'] = \app\admin\model\gas\Gasgun::where('gas_id', $item['id'])->select();
    	}
        $this->success('请求成功',$oil_list);
    }
    
    /**
     * 支付类型
     *
     */
    public function getpayway()
    {

    	$data = \app\admin\model\payment\Payway::select();

        $this->success('请求成功',$data);
    }
    
        /**
     * 支付方式
     *
     */
    public function getpay()
    {

    	$data = \app\admin\model\payment\Pay::select();

        $this->success('请求成功',$data);
    }
    
           /**
     * 商品信息
     *
     */
    public function getgoodslist()
    {
    	$store_no = $this->request->post('store_no');
    	$cat_id = $this->request->post('cat_id');
    	$data = \app\admin\model\goods_manage\Goods::where('store_no', $store_no)->where('cat_id', $cat_id)->select();

        $this->success('请求成功',$data);
    }
    
           /**
     * 商品信息
     *
     */
    public function getgoodsdetail()
    {
    	$store_no = $this->request->post('store_no');
    	$goods_id = $this->request->post('goods_id');
    	$data = \app\admin\model\goods_manage\Goods::where('store_no', $store_no)->where('id', $goods_id)->find();

        $this->success('请求成功',$data);
    }
    
           /**
     * 提交订单
     *
     */
    public function submit()
    {
//  	$user = $this->auth->getUser();
        $store_no = $this->request->post('store_no');
    	$type = $this->request->post('type');//2加油  3 商品
    	$goods_id = $this->request->post('goods_id');
    	$num = $this->request->post('num');//商品商量
    	$total_amount = $this->request->post('total_amount');//订单总额
    	$pay_type = $this->request->post('pay_type');//订单总额
    	$gas_id = $this->request->post('gas_id');
    	$gas_gun_id = $this->request->post('gas_gun_id');
//  	$store_no = 1;
//  	$type = 2;//2加油  3 商品
//  	$goods_id = 1;
//  	$num = 1;//商品商量
//  	$total_amount = 100;//订单总额
//  	$pay_type = 1;//订单总额
//  	$money = 200;
//  	$gas_id= 1;
//  	$gas_gun_id= 1;
    	if($pay_type == 1&&$total_amount > $user->money)$this->error('余额不足');
    	$osn = date('YmdHis') . rand(10000000,99999999);
    	if($type == 2)
    	{
    		$oil = \app\admin\model\gas\Gasset::where('id',$gas_id)->find();
    		if(!$oil)$this->error('油号不存在');
    		$paramgas['agent_id']=1;
	        $paramgas['store_no']=1;
	        $paramgas['user_id']=$user->id;
	        $paramgas['order_no']=$osn;
	        $paramgas['total_price']=$total_amount;
	        $paramgas['total_pay_price']=$total_amount;
	        $paramgas['discount_price']=0;
	        $paramgas['is_pay']=1;
	        $paramgas['pay_type']=$pay_type;
	        $paramgas['pay_time']=time();
	        $paramgas['source_type']=1;
    		$resultgas = \app\admin\model\exchange\Ordergas::create($paramgas);
    		if($resultgas)
    		{
    			$num = round($total_amount/$oil['price'],2);
    			//订单详情
    			$paraminfo['agent_id']=1;
		        $paraminfo['store_no']=1;
		        $paraminfo['order_id']=$resultgas['id'];
		        $paraminfo['gas_gun_id']=$gas_gun_id;
		        $paraminfo['num']=$num;
		        $paraminfo['unit_price']=$oil['price'];
		        $paraminfo['total_price']=$total_amount;
		        $paraminfo['unit']=$oil['unit'];

	    		$resultinfo = \app\admin\model\exchange\OrderGasInfo::create($paraminfo);
	    		//录入总订单
	    		$params['agent_id']=1;
		        $params['store_no']=1;
		        $params['user_id']=$user->id;
		        $params['order_no']=$osn;
		        $params['total_price']=$total_amount;
		        $params['total_pay_price']=$total_amount;
		        $params['discount_price']=0;
		        $params['is_pay']=1;
		        $params['pay_type']=$pay_type;
		        $params['type']=$type;
		        $params['source_type']=1;
		        $params['pay_time']=time();
		    
		    	$result = \app\admin\model\exchange\Order::create($params);
		    	$before = $user->money;
		    	$money = $user->money - $total_amount;
		    	$user->money = $money;
                $user->save();
                $memo = '油品下单';
                //写入日志
                $resultmo = \app\common\model\MoneyLog::create(['user_id' => $user->id, 'money' => $total_amount, 'before' => $before, 'after' => $money, 'memo' => $memo]);
		    	
		    	$this->success('支付成功');
    		}
    		
    		$this->error('支付失败');
    	}
    	if($type == 3)
    	{
    		$good = \app\admin\model\goods_manage\Goods::where('id',$goods_id)->find();
    		if(!$good)$this->error('商品不存在');
    		$paramgood['agent_id']=1;
	        $paramgood['store_no']=1;
	        $paramgood['user_id']=$user->id;
	        $paramgood['order_no']=$osn;
	        $paramgood['total_price']=$total_amount;
	        $paramgood['total_pay_price']=$total_amount;
	        $paramgood['discount_price']=0;
	        $paramgood['is_pay']=1;
	        $paramgood['pay_type']=$pay_type;
	        $paramgood['pay_time']=time();
	        $paramgood['source_type']=1;
    		$resultgood = \app\admin\model\exchange\Ordergoods::create($paramgood);
    		if($resultgood)
    		{
    	
    			//订单详情
    			$paraminfo['agent_id']=1;
		        $paraminfo['store_no']=1;
		        $paraminfo['order_id']=$resultgood['id'];
		        $paraminfo['goods_id']=$goods_id;
		        $paraminfo['num']=$num;
		        $paraminfo['unit_price']=$good['price'];
		        $paraminfo['total_price']=$total_amount;
		        $paraminfo['goods_sku']=$good['sku'];

	    		$resultinfo = \app\admin\model\exchange\OrderGoodsInfo::create($paraminfo);
	    		//录入总订单
	    		$params['agent_id']=1;
		        $params['store_no']=1;
		        $params['user_id']=$user->id;
		        $params['order_no']=$osn;
		        $params['total_price']=$total_amount;
		        $params['total_pay_price']=$total_amount;
		        $params['discount_price']=0;
		        $params['is_pay']=1;
		        $params['pay_type']=$pay_type;
		        $params['type']=$type;
		        $params['source_type']=1;
		        $params['pay_time']=time();
		    
		    	$result = \app\admin\model\exchange\Order::create($params);
		    	$before = $user->money;
		    	$money = $user->money - $total_amount;
		    	$user->money = $money;
                $user->save();
                $memo = '商品下单';
                //写入日志
                $resultmo = \app\common\model\MoneyLog::create(['user_id' => $user->id, 'money' => $total_amount, 'before' => $before, 'after' => $money, 'memo' => $memo]);
		    	
		    	$this->success('支付成功');
    		}
    		
    		$this->error('支付失败');
    	}
    	$this->error('支付失败');
    }
    
           /**
     * 订单列表
     *
     */
    public function orderlist()
    {
    	$user = $this->auth->getUser();
    	$type = $this->request->post('type');//2加油  3 商品
    	
    	$data['oil_list'] = \app\admin\model\gas\Gasset::where('store_no', $store_no)->select();
    	$data['store_detail'] = \app\admin\model\system_config\Storeset::where('store_no', $store_no)->find();
    	foreach ($data['oil_list'] as $index => $item) {
    		$item['gun'] = \app\admin\model\gas\Gasgun::where('gas_id', $item['id'])->select();
    	}
    }
     public function payment()
    {
        /*商户私钥*/
        $private_key ="MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCQMqL/T97RhAophQNRzBwE+vU+59PzfkEzyLZwMaQTduHvdTl4fg6KZ6ATFUgECI2JLpZq3cyjVYSlM9H20bRpZSaoYmsYyNibpf2lg+bMg9G+bS6elHvFn0ZJ+aU40wyWqPjtdLB9JYLDbLVsb6SzHegWovWeWD7vUqCbPhDK24V///baX2zV4609kfa1iBGbynF/0nggHw3leeUW9F8E8twSEF15ObE8ShywOMvi578kv9PUNmSiq8gfc/t8dWVOzi4mbDje49MhxMbuopGv1kcvHBrThTeqQ2plhQSs63AbwLpe4WsZbcNvG9zpjuci8bK1+Zb/3DnkmT4zEu6FAgMBAAECggEAHsQfEPhaoztX67nslmRF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vM+I8FDqwE3VcbmFlEJPnC4hQvwK3JjAju6FGhDgoB98rihcaUlsJfoTvrSmkLAmQOH8DW+a0UVbcCMp7TtWgpC8UMT0adAb/4ngQhjYuED4pI=";

        $request = new YopRequest("app_10088909942", $private_key);

        //加入请求参数
        $request->addParam("parentMerchantNo",'10088909942');
        $request->addParam("merchantNo",'10088970121');
        $request->addParam("orderId",'12312312414114');
        $request->addParam("orderAmount",11);
        $request->addParam("expiredTime",'');
        $request->addParam("notifyUrl",'');
        $request->addParam("redirectUrl",'');
        $request->addParam("memo",'');
        $request->addParam("goodsName",'BINGGAN');
        $request->addParam("fundProcessType",'');
        $request->addParam("payWay",'MINI_PROGRAM');
        $request->addParam("channel", 'WECHAT');
        $request->addParam("scene", 'OFFLINE');
        $request->addParam("appId", 'wx36cbd21e9ad4ea77');
        $request->addParam("userId", 'ovr9i4yBLu5mI--pgxqgOvuLsNlc');
        $request->addParam("userIp", '123.123.123.123');
        $request->addParam("intNum", 56);
        $request->addParam("bigDecimalNum", 1.2);
        $request->addParam("longNum", 789);
//      //提交Post请求
        $response = YopRsaClient::post("/rest/v1.0/aggpay/pre-pay", $request);

    	$this->error($response);
    }
    public function sandpayment()
    {
        
        $request = new HmPayClient();

        $url = $request->gatewayUrl;

        $appId = '552021071325659';
        $subAppId = $request->subAppId;
        $method = "trade.percreate";
        $format = $request->format;
        $charset = $request->charset;
        $signType = $request->signType;
        $version = $request->apiVersion;
        $timestamp = date("Y-m-d h:i:s");
        $nonce = $request->getRandStr(8);
        $privateKey = $request->rsaPrivateKey;
        //支付方式
        $payWay = "WECHAT";
        $createIp = "127.0.0.1";//生产环境使用真实ip
        $createTime = date("YmdHis");
        $expireTime = date("YmdHis", strtotime("+10 minute"));//过期时间
        $totalAmount = 1.00;
        $outOrderNo = $request->buildOrderNo();
        //商品详情 -- 按实际填写 或不填不上送
        $goodsDetail1 = array();
        $goodsDetail1['goods_id'] = 'a01';
        $goodsDetail1['goods_name'] = 'a1';
        $goodsDetail1['quantity'] = '1';
        $goodsDetail1['price'] = '0.01';

        $goodsDetail2 = array();
        $goodsDetail2['goods_id'] = 'a02';
        $goodsDetail2['goods_name'] = 'a2';
        $goodsDetail2['quantity'] = '1';
        $goodsDetail2['price'] = '0.99';
        $goodsDetail = array($goodsDetail1, $goodsDetail2);
        //订单详情
        $body = "无人超市";
        //商户交易门店
        $storeId = "100001";
        //终端信息
        $deviceInfo = array();
        $deviceInfo['longitude'] = '121.506377';
        $deviceInfo['latitude'] = '31.245105';

        $notifyUrl = null;

        $bizContent = $request->tradePrecreate($payWay, $createIp, $createTime, $expireTime, $totalAmount, $outOrderNo, $goodsDetail, $body, $storeId, $notifyUrl);
        
        $response = $request->execute($url, $request->request($appId, $subAppId, $method, $format, $charset, $signType, $timestamp, $nonce, $version, $bizContent, $privateKey));
        
        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
        $this->error($jsonResp);
        try {
            $request->checkResponseSign($jsonResp, $request->platRsaPublicKey, $signType);
        } catch (Exception $e) {
            error_log($e->getMessage());
            //todo 验签异常或失败
        }
    }
}
